define([
    'require',
    'jquery',
    'api',
    'bigwe_utils',
    'message',
    'pagination',
    'unauthor',
    'bigwe_component',
], function(require, $) {
    var bwAuthor = require('unauthor'),
        ShowTitleMessage = require('message'),
        util = require('bigwe_component'),
        showTime = ShowTitleMessage.showTime;

    var returnParam = {},
        param = {},
        param_user = {
            p: 1,
            l: 20,
            done: 'user'
        };

    returnParam.init = function(data) {
        if (data) {
            param_user.app_id = param.appid = data.app_id;
            param.acount = data.login_account;
            param.org_id = data.original_id;
            param.verify = data.verify_type_info;
            param.page = true;

            record.init();
        }
    };

    var record = {
        init: function() {
            this.groupList();
            this.userList();
        },
        //得到用户组数据
        groupList: function() {
            $.ajax({
                type: 'post',
                url: '/user_analyzing/analyzing',
                data: {
                    app_id: param.appid,
                    done: 'group'
                },
                success: function(data) {
                    var data = typeof data === 'string' ? $.parseJSON(data) : data,
                        html = '',
                        _html = '';
                    if (data.ret == 0) {
                        html += '<ul>';
                        for (var i in data.data) {
                            var groups = data.data[i];

                            (groups.group_id == 1) ? (html += '<li class="li_black_list">') : (html += '<li>');
                            html += groups.group_name + '<span class="spa_gray">(' + groups.group_count + ')</span><input type="hidden" value="' + groups.group_id + '" class="group"><span class="btn_control">';
                            if (groups.group_id > 2)
                                html += '<span create-input-event="groupReset" title="重命名" class="iconfont icon-pen1 icon-Find"></span>&nbsp;<span delete-event="group" title="删除" class="glyphicon glyphicon-trash icon-delete"></span>';
                            html += '</span></li>';
                            _html += '<li class="change_group"><a>' + groups.group_name + '</a><input type="hidden" value="' + groups.group_id + '"></li>'
                        }
                        html += '</ul>';
                        len = data.data.length;
                    } else {
                        ShowTitleMessage.show('该公众号没有分组', showTime);
                    }
                    $('.div_groupbody').empty().append(html);
                    $('#menu').empty().append(_html);
                }
            })
        },
        userList: function() {
            if ($('#chb_user_checkall')[0].checked)
                $('#chb_user_checkall').removeAttr('checked'),
                $('#chb_user_checkall')[0].indeterminate = false;
            var len = 0;
            $.ajax({
                type: 'post',
                url: 'user_analyzing/analyzing',
                data: param_user,
                success: function(data) {
                    var data = typeof data === 'string' ? $.parseJSON(data) : data;
                    if (data.ret == '21000') { //未认证没同步
                        var author_data = {
                            login_account: param.acount,
                            appid: param.appid
                        }
                        if (!param.acount) {
                            author_data.isNewAuthor = !0
                        }
                        bwAuthor.doAuthorOperate(author_data, function(data) {
                            if (!param.acount && data.login_account) {
                                param.acount = data.login_account;
                            }
                            $.ajax({
                                type: 'post',
                                url: '/interact/wechat/user_analyzing/get_sync_sim_followers',
                                timeout: 2000,
                                data: {
                                    login_account: param.acount,
                                    app_id: param.appid,
                                },
                                complete: function(data) {
                                    ShowTitleMessage.show('数据同步中，请注意系统通知', 1500);
                                }
                            });
                        });
                        return;
                    };

                    if (data.ret == '20011') {
                        ShowTitleMessage.show(data.msg, showTime);
                        return;
                    }
                    if (data.data.user) {
                        ShowTitleMessage.show('正在加载用户数据');
                        record.list(data.data.user);
                        $(".selectpicker").selectpicker({ size: 8, dropupAuto: false });
                        if (param.page) {
                            record.paging(data.data.total_page);
                        }
                        len = data.data.total;
                    } else {
                        $('#tbody').html('<p class="no_data">没有用户数据！</p>');
                        ShowTitleMessage.showWarning('没有用户数据！', showTime);
                    }
                    $('.div_grouphead > span').html('( ' + len + ' )');
                }
            })
        },
        list: function(arts) {
            var _html = '';
            for (var i in arts) {
                var art = arts[i];
                _html += '<tr data-group="' + art.groupid + '"><td>' +
                    '<input type="checkbox" class="checkbox" value="' + art.openid + '"/>' +
                    '</td><td><img class="img_user_face" alt="" src="' + art.headimgurl + '"></td>';
                if (art.remark) {
                    _html += '<td><input type="hidden" value="' + art.openid + '" class="openid">' + '<span class="user_name">' + art.remark + '</span>' + '<span class="spa_gray">(' + art.name + ')</span></td>';
                } else {
                    _html += '<td><input type="hidden" value="' + art.openid + '" class="openid">' + '<span class="user_name">' + art.name + '</span><span class="spa_gray"></span></td>';
                }
                _html += '<td><select class="selectpicker verifi" data-width="95px" openid="' + art.openid + '">';
                for (var j in art.group) {
                    var _art = art.group[j];
                    if (_art.group_id == art.groupid) {
                        _html += '<option selected = "selected" data-group="' + _art.group_id + '">' + _art.group_name + '</option>';
                    } else {
                        _html += '<option data-group="' + _art.group_id + '">' + _art.group_name + '</option>';
                    }
                }
                _html += '</select><button type="button" class="bigwe_default_btn_fff" create-input-event="note">修改备注</button></td></tr>';
            }
            $('#tbody').html(_html);
            ShowTitleMessage.hide();
        },
        paging: function(pg) {
            if (pg > 1)
                $('.paging').show();
            else
                $('.paging').hide();
            $('.paging').pagination(pg * 20, {
                num_edge_entries: 2,
                num_display_entries: 4,
                items_per_page: 20,
                prev_text: '上一页',
                next_text: '下一页',
                callback: function(_index, jq) {
                    if (param.page) {
                        return;
                    } else {
                        param_user.p = _index + 1;
                        record.userList();
                    }
                }
            });
            param.page = false;
        },
    }

    /*全选单选*/
    $("#chb_user_checkall").change(check_change);
    $(".div_detail_scroll").on("change", ".checkbox", check_change);

    function check_change() {
        if ($(this).attr('id') == 'chb_user_checkall') {
            if ($(this)[0].checked) {
                $(".div_detail_scroll :checkbox").prop('checked', true);
            } else {
                $(".div_detail_scroll :checkbox").removeAttr('checked');
            }
        } else {
            var graphLen = $('.div_detail_scroll input[type="checkbox"]').length,
                checkLen = $('.div_detail_scroll :checked').length;
            var $checkAll = $("#chb_user_checkall");
            if (checkLen == 0) {
                $checkAll[0].indeterminate = false;
                $checkAll.removeAttr('checked');
            } else {
                if (graphLen != checkLen) {
                    $checkAll[0].indeterminate = true;
                } else {
                    $checkAll.prop('checked', 'checked');
                    $checkAll[0].indeterminate = false;
                }
            }
        }
    }

    function gzh_login(fn) {
        var authordata = {
            appid: param.appid,
            login_account: param.acount,
        }
        if (!param.acount) {
            authordata.isNewAuthor = !0
        } else {
            authordata.isNewAuthor = 0;
        }
        bwAuthor.doAuthorOperate(authordata, function(data) {
            param.acount = data.login_account;
            fn();
        });
    }

    /*移动分组*/
    var grouping_data;
    var btn_click = false;
    $('.user_detail_scroll').on('change', '.selectpicker', function(e) {
        var group_id_old = $(this).parents('tr').data('group'),
            select_val = $(this).find("option:selected").data('group'),
            openid = $(this).attr("openid");

        $(this).parents('tr').data('group', select_val).attr('data-group', select_val);
        grouping_data = {
            app_id: param.appid,
            openid: openid,
            group_id_old: group_id_old,
            groupid: select_val,
            done: 'change'
        };
        if (param.verify == -1) {
            gzh_login(mobile_packet);
        } else {
            mobile_packet();
        }
    })

    /*批量移动*/
    $(document).on('click', '.change_group', function() {
        btn_click = true;
        var group_id = $(this).find('input').val(),
            group_name = $(this).text(),
            obj = document.getElementsByClassName('checkbox'),
            group_id_old = [],
            open_id = [];
        var j = 0;
        for (var i = 0; i < obj.length; i++) {
            if (obj[i].checked) {
                open_id[j] = obj[i].value;
                group_id_old[j] = obj[i].parentNode.parentNode.getAttribute('data-group');
                obj[i].parentNode.parentNode.setAttribute('data-group', group_id);
                obj[i].parentNode.nextSibling.nextSibling.nextSibling.firstChild.firstChild.firstChild.innerHTML = group_name;
                j++;
            }
        }
        if (open_id.length == 0) {
            ShowTitleMessage.show('请选择用户', showTime);
            return;
        }
        grouping_data = {
            app_id: param.appid,
            open_id: open_id,
            group_id: group_id,
            group_id_old: group_id_old,
            done: 'change_more'
        }
        if (param.verify == -1) {
            gzh_login(mobile_packet);
        } else {
            mobile_packet();
        }
    });

    function mobile_packet() {
        ShowTitleMessage.show('正在移动分组');
        $.ajax({
            type: 'post',
            url: '/user_analyzing/analyzing',
            data: grouping_data,
            success: function(data) {
                var data = typeof data === 'string' ? $.parseJSON(data) : data;
                if (data.ret == 0) {
                    ShowTitleMessage.show('分组移动成功', showTime);
                    if (btn_click) {
                        record.init();
                        btn_click = false;
                    } else {
                        record.groupList();
                    }
                } else {
                    ShowTitleMessage.showWarning(data.msg, showTime)
                }
            }
        })
    }
    /**
     * 修改备注按钮绑定事件
     */
    $(document).on('click', '[create-input-event="note"]', function() {
        var openid = $(this).siblings().find('select').attr('openid');
        var $this = $(this);
        CreatGroupPopup.init(this, {
            align: 'center',
            title: "备注名称",
            size: 30,
            value: ""
        }, function() {
            var remark = $('#popup_input>.txt_input>input').val();
            ShowTitleMessage.show('正在修改备注名');
            $.post('user_analyzing/analyzing', {
                app_id: param.appid,
                openid: openid,
                remark: remark,
                done: 'change_remark'
            }, function(data) {
                record.userList();
                ShowTitleMessage.show('备注修改成功', showTime);
                $('#popup_input').remove();
            });
        });
    });
    /**
     * 弹出菜单输入框
     * @param target 弹出附着对象
     * @param option.align 居中 居左 居右(相对于下面)
     * @param option.title 标题
     * @param option.value 输入框的默认值
     * @param option.size 字数限制
     * @param fn 点击确定后执行的回调
     */
    var CreatGroupPopup = {
        init: function(target, option, fn, event) {
            if (event) {
                event.stopPropagation();
            }
            $("#popup_input").remove();
            var jqTarget = $(target);
            var top = 0,
                left = 0,
                arrowRight = 0,
                arrowLeft = 0;
            var inputVal = typeof(option.value) === 'undefined' ? '' : option.value;
            var taHeight = jqTarget.height() +
                parseInt(jqTarget.css("padding-top")) +
                parseInt(jqTarget.css("padding-bottom")) +
                parseInt(jqTarget.css("border-top-width")) +
                parseInt(jqTarget.css("border-bottom-width"));
            var taWidth = jqTarget.width() +
                parseInt(jqTarget.css("padding-left")) +
                parseInt(jqTarget.css("padding-right")) +
                parseInt(jqTarget.css("border-left-width")) +
                parseInt(jqTarget.css("border-right-width"));
            top = jqTarget.offset().top + taHeight + 14;
            left = jqTarget.offset().left;
            $("body").append('<div id="popup_input" class="popup_input">' +
                '<img src="/Public/static/images/Triangle-up.png">' +
                '<p class="title">' + option.title + '</p>' +
                '<p class="txt_input"><input type="text" value="' + inputVal + '" maxlength="' + option.size + '"/><span><span id="textSizing">0</span><span>/' + option.size + '</span></span></p>' +
                '<p class="btn_p">' +
                '<button type="button" class="bigwe_default_btn btn-success">确定</button>' +
                '<button type="button" class="bigwe_default_btn_fff btn-default" onclick="$(this).parent().parent().remove()">取消</button>' +
                '</p>' +
                '</div>');
            var popWidth = $("#popup_input").width() + parseInt($("#popup_input").css("padding-left")) + parseInt($("#popup_input").css("padding-right")) + 2;
            if (option.align === "right") {
                left = left + taWidth - popWidth;
                arrowRight = taWidth / 2 - 12;
                $("#popup_input>img").css({
                    right: arrowRight
                });
            } else if (option.align === "custom") {
                // 自定义
                left = option.left;
                arrowRight = option.arrowRight;
                $("#popup_input>img").css({
                    right: arrowRight
                });
            } else {
                left = left + taWidth / 2 - popWidth / 2;
                arrowLeft = popWidth / 2 - 14;
                $("#popup_input>img").css({
                    left: arrowLeft
                });
            }
            $("#popup_input").css({
                top: top,
                left: left
            });
            $("#popup_input>.txt_input>input[type='text']").on("keyup", function() {
                var len = $(this).val().length;
                $(this).next("span").find("#textSizing").text(len);
            });
            $("#popup_input").fadeIn();
            $("#popup_input").find('input').focus();
            $(document).bind("click.popup_input", function(e) {
                CreatGroupPopup.closest(e);
            });
            $("#popup_input>.btn_p>.bigwe_default_btn").on("click", function() {
                if (param.verify == -1) {
                    gzh_login(rename);
                } else {
                    rename();
                }

                function rename() {
                    if (fn) {
                        fn($("#popup_input>.txt_input>input[type='text']").val());
                    }
                }
            });
        },
        closest: function(e) {
            var target = $(e.target);
            if (typeof(target.attr("create-input-event")) != 'undefined' && target.attr("create-input-event") != "") {
                return;
            }
            if (target.closest("#popup_input").length == 0) {
                $("#popup_input").remove();
                $(document).unbind("click.popup_input");
            }
        }
    };

    /*分组预览*/
    $(".div_grouphead").click(function(argument) {
        delete param_user.group_id
        record.userList();
    })

    $(".div_groupbody").on('click', 'li', function(argument) {
        group_id = $(this).find('.group').val();
        param.page = true;
        param_user.p = 1;
        param_user.group_id = group_id;
        record.userList();
    })

    /*搜索*/
    $('#usergroup_manage .search_btn').click(function() {
        var keyword = $('#search_text').val();
        param.page = true;
        param_user.p = 1;
        param_user.keyword = keyword;
        record.userList();
    });

    /*新建分组*/
    $(document).on('click', '[create-input-event="group"]', function() {
        CreatGroupPopup.init(this, {
            align: 'right',
            title: "分组名称",
            size: 6
        }, function() {
            var group_name = $('#popup_input>.txt_input>input').val();
            if (group_name == '') {
                ShowTitleMessage.show('新分组名不能为空', showTime);
                return;
            }
            ShowTitleMessage.show('正在创建分组', showTime);
            $.post('user_analyzing/analyzing', {
                app_id: param.appid,
                group_name: group_name,
                done: 'new_group'
            }, function(data) {
                $('#popup_input').remove();
                if (data == 1) {
                    ShowTitleMessage.show('新建分组成功。', showTime);
                    var ul = '';
                    var data = $.parseJSON(data);
                    ul += '<li class="change_group"><a>' + group_name + '</a><input type="hidden" value="' + data.group_id + '"></li>';
                    var opt = '';
                    opt = '<li data-original-index="' + data.group_id + '"><a tabindex="0" class="" style="" data-tokens="null"><span class="text">' + group_name + '</span><span class="glyphicon glyphicon-ok check-mark"></span></a></li>'
                    $('#menu').append(ul);
                    $('ul.dropdown-menu.inner').append(opt);
                    record.init();
                }
                if (data == -2) {
                    ShowTitleMessage.show('生成失败,用户组已存在。', showTime);
                    return;
                }
                if (data == -3) {
                    ShowTitleMessage.show('生成失败,未选择公众号。', showTime);
                    return;
                }

            });
        });
    });
    /**
     * 删除分组
     */
    $('.div_groupbody').on('click', '[delete-event]', function(e) {
        dynamicDeleteEvent(this, e);
    });

    function dynamicDeleteEvent(obj, event) {
        if (event) {
            event.stopPropagation();
        }
        var group_id = $(obj).parents('li').find('.group').val();
        util.deleteConfirmShowBottom({
            obj: obj,
            custom: function() {
                if (param.verify == -1) {
                    gzh_login(delete_ev);
                } else {
                    delete_ev();
                }

                function delete_ev() {
                    ShowTitleMessage.show('正在删除分组', showTime);
                    $.ajax({
                        type: 'post',
                        url: 'user_analyzing/analyzing',
                        data: {
                            app_id: param.appid,
                            param: group_id,
                            done: 'delete',
                        },
                        success: function(data) {
                            var data = typeof data === 'string' ? $.parseJSON(data) : data;
                            if (data.ret == 0) {
                                $('.delete_confirm').remove();
                                record.init();
                            } else {
                                ShowTitleMessage.showWarning(data.msg, showTime);
                            }
                        }
                    })
                }
            }
        });
    }
    /**
     * 重命名分组
     */
    $('.div_groupbody').on('click', '[create-input-event="groupReset"]', function(e) {
        e.stopPropagation();
        var group_id = $(this).parent().parent().find('.group').val();
        var app_id = $(".mail-sub>.list-sub-text>.app_id").val();
        CreatGroupPopup.init(this, {
            align: 'custom',
            title: "重命名分组",
            size: 6,
            value: "",
            left: $(this).parent().parent().parent().offset().left - 6,
            arrowRight: 33
        }, function() {
            var group_name = $('#popup_input>.txt_input>input').val();
            if (group_name == '') {
                ShowTitleMessage.show('分组名不能为空', showTime);
                return;
            }
            ShowTitleMessage.show('正在修改分组名');
            $.post('user_analyzing/analyzing', {
                app_id: param.appid,
                group_id: group_id,
                group_name: group_name,
                done: 'change_gname'
            }, function(data) {
                if (data == -2) {
                    ShowTitleMessage.show('生成失败,用户组已存在。', BwDefaultConstant.showTime);
                    return;
                }
                $('#popup_input').remove();
                record.init();
            });
        }, e);
    });

    return returnParam;
})
